package com.ldy.seal.util;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * Spring工具类
 * 
 * @version 1.0.0, 2018-05-04
 *
 */
@Component
public class SpringUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext;

	/**
	 * 设置 ApplicationContext 静态方法
	 * 
	 * @param ctx ApplicationContext
	 */
	public static void setStaticApplicationContext(ApplicationContext ctx) {
		SpringUtil.applicationContext = ctx;
	}

	/**
	 * Set the ApplicationContext that this object runs in.
	 * 
	 * @param applicationContext ApplicationContext
	 * @throws BeansException if thrown by application context methods
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		setStaticApplicationContext(applicationContext);
	}
	
	/**
	 * 根据接口获取实现该接口的全部Bean
	 * 
	 * @param clazz Class，例如：FaceCompareService.class
	 * @return Map<String, ?>
	 */
	public static Map<String, ?> getBeansOfType(Class<?> clazz) {
		return applicationContext != null ? applicationContext.getBeansOfType(clazz) : null;
	}

	/**
	 * 根据Class来获取Bean
	 * 
	 * @param clazz Class，例如：StudentMapper.class
	 * @return Object
	 */
	public static Object getBean(Class<?> clazz) {
		return applicationContext != null 
				? applicationContext.getBean(clazz)
				: null;
	}

	
	/**
	 * 根据beanName来获取Bean
	 * 
	 * @param beanName beanId或bean名称，例如：studentServiceImpl
	 * @return Object
	 */
	public static Object getBean(String beanName) {
		return applicationContext != null && applicationContext.containsBean(beanName)
				? applicationContext.getBean(beanName)
				: null;
	}

	/**
	 * 根据字符串的类名来获取Bean
	 * 
	 * @param stringClass 字符串的类名，例如：com.nja.biz.datax.common.JdbcInternalTask
	 * @return Object，返回null表示异常
	 */
	public static Object getBeanByStringClass(String stringClass) {
		try {
			Class<?> clazz = Class.forName(stringClass);
			return getBean(clazz);
		} catch (ClassNotFoundException e) {
			return null;
		}
	}
}
